package com.bdsoft.security.config;

import com.bdsoft.security.entity.OperationLogDTO;
import com.bdsoft.security.entity.SecurityUser;
import com.bdsoft.security.mapper.PermisstionMapper;
import com.bdsoft.security.service.ResourceService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.AuthorizationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.access.intercept.RequestAuthorizationContext;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.function.Supplier;

@Component
public class DynamicAuthorizationManager implements AuthorizationManager<RequestAuthorizationContext> {

    @Autowired
    private ResourceService resourceService;
    @Autowired
    private PermisstionMapper permisstionMapper;

    @Override
    public AuthorizationDecision check(Supplier<Authentication> authentication, RequestAuthorizationContext context) {
        HttpServletRequest request = context.getRequest();
        Map<String, String[]> params=request.getParameterMap();
        String url = request.getRequestURI();
        String method = request.getMethod();
        String resourceId = resourceService.getResourceIdByUrlAndMethod(url, method);
        Authentication auth = authentication.get();
        System.out.println("Authentication对象: " + auth);

        SecurityUser user = (SecurityUser) auth.getPrincipal();

        System.out.println(user);
        List<Map<String,Object>> roleList=user.getMenus();
        for (Map<String,Object> m :roleList){
            if (m.get("role_id").equals("r100")){
                OperationLogDTO operationLogDTO=new OperationLogDTO();
                UUID uuid=UUID.randomUUID();
                operationLogDTO.setLogId(uuid.toString());
                operationLogDTO.setIp(getIpAddress(request));
                operationLogDTO.setOperation(String.valueOf( permisstionMapper.getResourceByUrlAndMethod(url,method).get("description")));
                operationLogDTO.setMethod(method);
                operationLogDTO.setParams(params.toString());
                operationLogDTO.setUserId(user.getUser().getId());
                resourceService.addLog(operationLogDTO);
                return new AuthorizationDecision(true);
            }
        }
        if (resourceId == null) {
            throw new AccessDeniedException("无权限");
        }


        if (auth == null) {
            throw new AccessDeniedException("未认证");
        }

        Collection<? extends GrantedAuthority> authorities = auth.getAuthorities();
        for (GrantedAuthority authority : authorities) {
            if (resourceId.equals(authority.getAuthority())) {
                OperationLogDTO operationLogDTO=new OperationLogDTO();
                UUID uuid=UUID.randomUUID();
                operationLogDTO.setLogId(uuid.toString());
                operationLogDTO.setIp(getIpAddress(request));
                operationLogDTO.setOperation(String.valueOf( permisstionMapper.getResourceByUrlAndMethod(url,method).get("description")));
                operationLogDTO.setMethod(method);
                operationLogDTO.setParams(params.toString());
                operationLogDTO.setUserId(user.getUser().getId());
                resourceService.addLog(operationLogDTO);
                return new AuthorizationDecision(true);
            }
        }
        throw new AccessDeniedException("无权限");
    }
    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}